package cn.iocoder.yudao.module.biz.controller.admin.invoice;

import cn.iocoder.yudao.framework.excel.core.util.poi.ExcelUtilRuoyi;
import cn.iocoder.yudao.module.biz.controller.admin.invoice.domain.SanBizInvoiceContent;
import cn.iocoder.yudao.module.biz.controller.admin.invoice.domain.SanBizInvoiceManagement;
import cn.iocoder.yudao.module.biz.controller.admin.invoice.service.SanBizInvoiceContentService;
import cn.iocoder.yudao.module.biz.controller.admin.invoice.service.SanBizInvoiceManagementService;
import cn.iocoder.yudao.module.biz.controller.admin.pay.domain.SanBizPaymentManagement;
import cn.iocoder.yudao.module.biz.controller.admin.salesteam.vo.SanBizSalesTeamUser;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import org.apache.commons.lang3.StringUtils;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;
import javax.annotation.Resource;
import org.springframework.validation.annotation.Validated;
import org.springframework.security.access.prepost.PreAuthorize;
import io.swagger.v3.oas.annotations.tags.Tag;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.Operation;

import javax.validation.constraints.*;
import javax.validation.*;
import javax.servlet.http.*;
import java.util.*;
import java.io.IOException;

import cn.iocoder.yudao.framework.common.pojo.PageParam;
import cn.iocoder.yudao.framework.common.pojo.PageResult;
import cn.iocoder.yudao.framework.common.pojo.CommonResult;
import cn.iocoder.yudao.framework.common.util.object.BeanUtils;
import static cn.iocoder.yudao.framework.common.pojo.CommonResult.success;

import cn.iocoder.yudao.framework.excel.core.util.ExcelUtils;

import cn.iocoder.yudao.framework.apilog.core.annotation.ApiAccessLog;
import static cn.iocoder.yudao.framework.apilog.core.enums.OperateTypeEnum.*;


@Tag(name = "管理后台 - 发票管理")
@RestController
@RequestMapping("/invoice/biz-invoice-management")
@Validated
public class BizInvoiceManagementController {

    @Resource
    private SanBizInvoiceManagementService bizInvoiceManagementService;

    @Resource
    private SanBizInvoiceContentService contentService;

    @PostMapping("/create")
    @Operation(summary = "创建发票管理")
    @PreAuthorize("@ss.hasPermission('invoice:biz-invoice-management:create')")
    @Transactional
    public CommonResult<Long> createBizInvoiceManagement(@Valid @RequestBody SanBizInvoiceManagement createReqVO) {
        bizInvoiceManagementService.save(createReqVO);
        QueryWrapper<SanBizInvoiceContent> wrapper = new QueryWrapper<>();
        wrapper.eq("invoice_id", createReqVO.getId());
        createReqVO.getItems().forEach(a -> {
            a.setInvoiceId(Long.valueOf(createReqVO.getId()));
            a.setId(null);
        });
        contentService.remove(wrapper);
        contentService.saveBatch(createReqVO.getItems());
        return success(1l);
    }

    @PutMapping("/update")
    @Operation(summary = "更新发票管理")
    @PreAuthorize("@ss.hasPermission('invoice:biz-invoice-management:update')")
    @Transactional
    public CommonResult<Boolean> updateBizInvoiceManagement(@Valid @RequestBody SanBizInvoiceManagement updateReqVO) {
        bizInvoiceManagementService.updateById(updateReqVO);
        QueryWrapper<SanBizInvoiceContent> wrapper = new QueryWrapper<>();
        wrapper.eq("invoice_id", updateReqVO.getId());
        if(updateReqVO.getItems() != null){
            updateReqVO.getItems().forEach(a -> {
                a.setInvoiceId(Long.valueOf(updateReqVO.getId()));
            });
        }
       if(StringUtils.isNotEmpty(updateReqVO.getTaxIdNumber())){
           contentService.remove(wrapper);
           contentService.saveBatch(updateReqVO.getItems());
       }

        return success(true);
    }

    @DeleteMapping("/delete")
    @Operation(summary = "删除发票管理")
    @Parameter(name = "id", description = "编号", required = true)
    @PreAuthorize("@ss.hasPermission('invoice:biz-invoice-management:delete')")
    public CommonResult<Boolean> deleteBizInvoiceManagement(@RequestParam("id") Long id) {
        bizInvoiceManagementService.removeById(id);
        return success(true);
    }

    @DeleteMapping("/delete-list")
    @Parameter(name = "ids", description = "编号", required = true)
    @Operation(summary = "批量删除发票管理")
                @PreAuthorize("@ss.hasPermission('invoice:biz-invoice-management:delete')")
    public CommonResult<Boolean> deleteBizInvoiceManagementList(@RequestParam("ids") List<Long> ids) {
        bizInvoiceManagementService.removeByIds(ids);
        return success(true);
    }

    @GetMapping("/get")
    @Operation(summary = "获得发票管理")
    @Parameter(name = "id", description = "编号", required = true, example = "1024")
    @PreAuthorize("@ss.hasPermission('invoice:biz-invoice-management:query')")
    public CommonResult<SanBizInvoiceManagement> getBizInvoiceManagement(@RequestParam("id") Long id) {
        SanBizInvoiceManagement bizInvoiceManagement = bizInvoiceManagementService.getById(id);
        return success(BeanUtils.toBean(bizInvoiceManagement, SanBizInvoiceManagement.class));
    }

    @GetMapping("/page")
    @Operation(summary = "获得发票管理分页")
    @PreAuthorize("@ss.hasPermission('invoice:biz-invoice-management:query')")
    public CommonResult<IPage<SanBizInvoiceManagement>> getBizInvoiceManagementPage(@Valid SanBizInvoiceManagement pageReqVO) {
        IPage<SanBizInvoiceManagement> pageResult = bizInvoiceManagementService.getBizInvoiceManagementPage(pageReqVO);
        return success(pageResult);
    }

    @GetMapping("/export-excel")
    @Operation(summary = "导出发票管理 Excel")
    @PreAuthorize("@ss.hasPermission('invoice:biz-invoice-management:export')")
    @ApiAccessLog(operateType = EXPORT)
    public void exportBizInvoiceManagementExcel(@Valid SanBizInvoiceManagement pageReqVO,
              HttpServletResponse response) throws IOException {
//        pageReqVO.setPageSize(PageParam.PAGE_SIZE_NONE);
//        List<BizInvoiceManagementDO> list = bizInvoiceManagementService.getBizInvoiceManagementPage(pageReqVO).getList();
//        // 导出 Excel
//        ExcelUtils.write(response, "发票管理.xls", "数据", SanBizInvoiceManagement.class,
//                        BeanUtils.toBean(list, SanBizInvoiceManagement.class));
        QueryWrapper w = new QueryWrapper(pageReqVO);
        List<SanBizInvoiceManagement> list = bizInvoiceManagementService.list(w);
        // 导出 Excel
//        ExcelUtils.write(response, "打款记录.xls", "数据", SanBizPaymentManagement.class,
//                        BeanUtils.toBean(list, SanBizPaymentManagement.class));
        ExcelUtilRuoyi<SanBizInvoiceManagement> util = new ExcelUtilRuoyi<SanBizInvoiceManagement>(SanBizInvoiceManagement.class);
        util.exportExcel(response, list, "发票列表");
    }

    @GetMapping("/getItems")
    @Operation(summary = "获得发票内容")
    @Parameter(name = "id", description = "发票ID", required = true, example = "1")
    @PreAuthorize("@ss.hasPermission('invoice:biz-invoice-management:query')")
    public CommonResult<List<SanBizInvoiceContent>> getItems(@RequestParam("id") Long id) {
        QueryWrapper w = new QueryWrapper();
        w.eq("invoice_id",id);
        List<SanBizInvoiceContent> list = contentService.list(w);
        return success(list);
    }

}